package com.tucc.hello.juc;

import lombok.SneakyThrows;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.juc
 * @date 2021/6/1
 **/
public class SemaphoreDemo {


    Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) {
        SemaphoreDemo demo = new SemaphoreDemo();
        demo.start();
    }

    public void start(){
        for(int i = 0;i < 10;i ++){
            new TaskThread(i).start();
        }
    }

    class TaskThread extends Thread{

        int num;

        TaskThread(int num){
            this.num = num;
        }
        @SneakyThrows
        @Override
        public void run() {
            semaphore.acquire();
            System.out.println("Thread-" + num + " get semaphore");
            TimeUnit.SECONDS.sleep(3);
            System.out.println("Thread-" + num + " release semaphore");
            semaphore.release();
        }
    }
}
